package com.zjsru.binaryeasy;

import java.util.Arrays;

/**
 * @Author: likew
 * @Date: 2022/8/6
 * x 的平方根
 * 输入：x = 4
 * 输出：2
 */
public class MySqrt {
    /**
     * 调用pow库
     */
    public int mySqrt1(int x) {
        int pow =(int) Math.pow(x, 0.5);
        return pow;
    }
    
    /**
     * 使用二分算法
     */
    public int mySqrt(int x) {
        int r = x, l = 0, ans = -1;
        while(r >= l){
            int mid = (r - l)/2 + l;
            long mul = (long) mid * mid;
            if(mul <= x){
                ans = mid;
                l = mid + 1;
            }else {
                r = mid - 1;
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        MySqrt mySqrt = new MySqrt();
        int x = 2147395599;
        System.out.println(mySqrt.mySqrt(x));
    }
}
